package com.utry.netty;

import android.os.Bundle;
import android.os.Looper;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.utry.netty.base.BaseActivity;
import com.utry.netty.bean.PkgDataBean;
import com.utry.netty.client.NettyClient;
import com.utry.netty.intf.ConnectClientCallback;
import com.utry.netty.intf.MessageClientCallback;
import com.utry.netty.intf.MessageServerCallback;
import com.utry.netty.server.NettyServer;
import com.utry.netty.server.ServerHandler;
import com.utry.netty.websocket.NettyStocktakingUtil;

import java.util.List;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

public class MainActivity extends BaseActivity implements View.OnClickListener, MessageClientCallback {

    private static final String TAG = "MainActivity";
    private TextView tvLog;
    private TextView tvTest;
    private EditText etContent;
    NettyServer nettyServer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvTest = findViewById(R.id.tv_test);
        String sf = String.format(getResources().getString(R.string.card_ded23456), "<font color='#FF0000'>" + 2 + "</font>");
        tvTest.setText(Html.fromHtml(sf));
        setTitle("Netty在Android中的应用");
        initView();
    }

    private void initView() {
        tvLog = findViewById(R.id.tv_log);
        etContent = findViewById(R.id.et_content);
        findViewById(R.id.btn_start_server).setOnClickListener(this);
        findViewById(R.id.btn_connect).setOnClickListener(this);
        findViewById(R.id.btn_send).setOnClickListener(this);
        findViewById(R.id.btn_pkg).setOnClickListener(this);
        findViewById(R.id.btn_connect_web).setOnClickListener(this);
        findViewById(R.id.btn_web_send).setOnClickListener(this);

//        NettyUtil.getInstance().nettyConnect(new MessageClientCallback() {
//            @Override
//            public void messageClientCallback(final String message) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        setText(message);
//                    }
//                });
//            }
//        });
    }

    private void setText(String message) {
        Log.v("NETWORKURL1", message + tvLog.getId());
        tvLog.append(message + "\n");
    }

    public boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_server:
                nettyServer = new NettyServer();
                nettyServer.setMessageServerCallback(new MessageServerCallback() {
                    @Override
                    public void messageServerCallback(final String message) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                tvLog.append(message + "\n\n");
                            }
                        });
                    }
                });
                nettyServer.startServer();
                break;
            case R.id.btn_pkg:
                List<ChannelHandlerContext> channels = ServerHandler.channels;
                for (ChannelHandlerContext ctx : channels) {
                    for (int i = 0; i < 3; i++) {
                        PkgDataBean bean = new PkgDataBean();
                        bean.setCmd((byte) 0x05);
                        bean.setData("粘包的数据：" + i);
                        bean.setDataLength((byte) bean.getData().getBytes().length);
                        ctx.channel().writeAndFlush(bean);
                    }
                }
                Log.d(TAG, "服务端发送了粘包数据");
                break;
            case R.id.btn_connect:
                NettyClient client = NettyClient.getInstance();
                client.setMessageClientCallback(MainActivity.this::messageClientCallback);
                break;
            case R.id.btn_send:
                Channel channel = NettyClient.getChannel();
                if (channel == null) {
                    Toast.makeText(this, "请先连接TCP服", Toast.LENGTH_SHORT).show();
                } else {
                    setNettyMessage(channel);
                }
                break;
            case R.id.btn_connect_web:
                NettyStocktakingUtil.getInstance().nettyConnect(new ConnectClientCallback() {
                    @Override
                    public void onConnect(int code, String message) {
                        runOnUiThread(() -> {
                            tvLog.append(message + "\n");
                            NettyStocktakingUtil.getInstance().setMessageClientCallback(MainActivity.this::messageClientCallback);
                        });
                    }
                });
                break;

            case R.id.btn_web_send:
                NettyStocktakingUtil.getInstance().setNettyPost("online.1-2-1-B-1");

                break;
            default:
                break;
        }
    }

    private final Object object = new Object();

    private void setNettyMessage(Channel channel) {
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                synchronized (object) {
                    int finalI = i;
                    Log.v(TAG, String.valueOf(finalI));
                    PkgDataBean bean = new PkgDataBean();
                    bean.setCmd((byte) 0x02);
                    bean.setData(String.valueOf(finalI));
                    bean.setDataLength((byte) bean.getData().getBytes().length);
                    channel.writeAndFlush(bean);
                    try {
                        object.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        Log.v("NETWORKURL", "guanbi");
//        if (nettyServer != null)
//            nettyServer.shutdown();
        NettyClient.getInstance().destroy();
        super.onDestroy();

    }

    @Override
    public void messageClientCallback(String message) {
        runOnUiThread(() -> {
            Log.v(TAG, String.valueOf(message));
            tvLog.append(message + "\n");
            synchronized (object) {
                try {
                    object.notifyAll();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
